<template>
  <view class="page">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 顶部导航栏 -->
    <view class="navbar">
      <text class="nav-title">便签</text>
      <view class="nav-add" @click="showCreateDialog">
        <uni-icons type="plus" size="24" color="#fff"></uni-icons>
      </view>
    </view>

    <!-- 便签列表 -->
    <view class="content" v-if="notesList.length > 0">
      <view class="notes-list">
        <view
          class="note-item"
          v-for="item in notesList"
          :key="item.id"
          @click="editNote(item)"
        >
          <view class="note-info">
            <view class="note-header">
              <text class="note-title">{{ item.title || '无标题' }}</text>
              <view class="note-actions" @click.stop>
                <view class="action-btn" @click="deleteNote(item.id)">
                  <uni-icons type="trash" size="16" color="#F44336"></uni-icons>
                </view>
              </view>
            </view>
            <view class="note-content">
              <text class="content-preview">{{ getContentPreview(item.content) }}</text>
            </view>
            <view class="note-time">
              <text class="time-text">修改时间：{{ formatTime(item.updateTime) }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <view class="empty-icon">
        <uni-icons type="compose" size="80" color="#ccc"></uni-icons>
      </view>
      <text class="empty-text">暂无便签</text>
      <text class="empty-hint">点击右上角 + 新建便签</text>
    </view>

    <!-- 创建/编辑便签弹窗 -->
    <uni-popup ref="notePopup" type="bottom" :safe-area="false">
      <view class="note-container">
        <view class="note-header-popup">
          <text class="note-title-popup">{{ formMode === 'create' ? '新建便签' : '编辑便签' }}</text>
          <view class="note-close" @click="closeNoteDialog">
            <uni-icons type="closeempty" size="20" color="#999"></uni-icons>
          </view>
        </view>

        <view class="note-form">
          <view class="form-item">
            <view class="form-label-wrapper">
              <text class="form-label">便签标题</text>
              <text class="char-count" :class="{ 'over-limit': noteForm.title.length > MAX_TITLE_LENGTH }">
                {{ noteForm.title.length }}/{{ MAX_TITLE_LENGTH }}
              </text>
            </view>
            <input
              class="form-input"
              v-model="noteForm.title"
              placeholder="请输入便签标题"
              :maxlength="MAX_TITLE_LENGTH"
            />
          </view>

          <view class="form-item">
            <view class="form-label-wrapper">
              <text class="form-label">便签内容</text>
              <text class="char-count" :class="{ 'over-limit': noteForm.content.length > MAX_CONTENT_LENGTH }">
                {{ noteForm.content.length }}/{{ MAX_CONTENT_LENGTH }}
              </text>
            </view>
            <textarea
              class="form-textarea"
              v-model="noteForm.content"
              placeholder="请输入便签内容..."
              :maxlength="MAX_CONTENT_LENGTH"
              :auto-height="true"
            ></textarea>
          </view>
        </view>

        <view class="note-actions">
          <button class="note-btn cancel" @click="closeNoteDialog">取消</button>
          <button class="note-btn confirm" @click="submitNote" :disabled="!isFormValid">
            {{ formMode === 'create' ? '创建' : '保存' }}
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { notesApi } from '@/api/index.js';


uni.setNavigationBarTitle({
  title: '便签'
});

// 长度限制常量
const MAX_TITLE_LENGTH = 30;
const MAX_CONTENT_LENGTH = 500;

// 系统信息
const statusBarHeight = ref(0);

// 便签列表
const notesList = ref([]);

// 弹窗引用
const notePopup = ref(null);

// 表单模式：'create' 或 'edit'
const formMode = ref('create');

// 当前编辑的便签ID
const editingNoteId = ref(null);

// 创建/编辑表单
const noteForm = reactive({
  title: '',
  content: ''
});

// 计算属性
const isFormValid = computed(() => {
  const titleLength = noteForm.title.trim().length;
  const contentLength = noteForm.content.trim().length;

  // 至少有标题或内容，且都不超过长度限制
  return (titleLength > 0 || contentLength > 0) &&
         titleLength <= MAX_TITLE_LENGTH &&
         contentLength <= MAX_CONTENT_LENGTH;
});

// 页面初始化
onMounted(() => {
  // 获取系统信息
  const systemInfo = uni.getSystemInfoSync();
  statusBarHeight.value = systemInfo.statusBarHeight || 0;

  // 加载便签列表
  loadNotesList();
});

// 加载便签列表
const loadNotesList = async () => {
  try {
    const response = await notesApi.getNotesList({
      page: 0,
      size: 100,
      sort: 'updateTime,desc'
    });

    if (response.code === 200) {
      notesList.value = response.data.content || [];
    } else {
      throw new Error(response.message || '加载失败');
    }
  } catch (error) {
    console.error('加载便签列表失败:', error);
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    });
    // 降级到本地存储
    loadNotesFromLocal();
  }
};

// 从本地存储加载便签（降级方案）
const loadNotesFromLocal = () => {
  try {
    const storedNotes = uni.getStorageSync('notesList');
    if (storedNotes) {
      notesList.value = JSON.parse(storedNotes);
    }
  } catch (error) {
    console.error('从本地加载便签失败:', error);
    notesList.value = [];
  }
};

// 保存便签列表到本地存储（备份）
const saveNotesToLocal = () => {
  try {
    uni.setStorageSync('notesList', JSON.stringify(notesList.value));
  } catch (error) {
    console.error('保存便签到本地失败:', error);
  }
};

// 格式化时间
const formatTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';

  // 处理后端返回的LocalDateTime格式
  const date = new Date(dateTimeStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  // 小于1分钟
  if (diff < 60000) {
    return '刚刚';
  }

  // 小于1小时
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`;
  }

  // 小于1天
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`;
  }

  // 大于1天，显示具体日期
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 获取内容预览
const getContentPreview = (content) => {
  if (!content) return '暂无内容';
  // 增加字符限制，配合CSS的多行截断
  return content.length > 80 ? content.substring(0, 80) + '...' : content;
};

// 显示创建弹窗
const showCreateDialog = () => {
  formMode.value = 'create';
  editingNoteId.value = null;
  resetNoteForm();
  notePopup.value.open();
};

// 编辑便签
const editNote = (note) => {
  formMode.value = 'edit';
  editingNoteId.value = note.id;
  noteForm.title = note.title;
  noteForm.content = note.content;
  notePopup.value.open();
};

// 关闭便签弹窗
const closeNoteDialog = () => {
  notePopup.value.close();
  resetNoteForm();
  formMode.value = 'create';
  editingNoteId.value = null;
};

// 重置表单
const resetNoteForm = () => {
  noteForm.title = '';
  noteForm.content = '';
};

// 提交便签
const submitNote = () => {
  const titleLength = noteForm.title.trim().length;
  const contentLength = noteForm.content.trim().length;

  // 检查是否有内容
  if (titleLength === 0 && contentLength === 0) {
    uni.showToast({
      title: '请输入标题或内容',
      icon: 'none'
    });
    return;
  }

  // 检查标题长度
  if (titleLength > MAX_TITLE_LENGTH) {
    uni.showToast({
      title: `标题不能超过${MAX_TITLE_LENGTH}个字符`,
      icon: 'none'
    });
    return;
  }

  // 检查内容长度
  if (contentLength > MAX_CONTENT_LENGTH) {
    uni.showToast({
      title: `内容不能超过${MAX_CONTENT_LENGTH}个字符`,
      icon: 'none'
    });
    return;
  }

  if (formMode.value === 'create') {
    createNote();
  } else {
    updateNote();
  }
};

// 创建便签
const createNote = async () => {
  try {
    const response = await notesApi.createNote({
      title: noteForm.title.trim(),
      content: noteForm.content.trim()
    });

    if (response.code === 200) {
      // 添加到列表开头
      notesList.value.unshift(response.data);
      // 备份到本地
      saveNotesToLocal();

      uni.showToast({
        title: '创建成功',
        icon: 'success'
      });

      closeNoteDialog();
    } else {
      throw new Error(response.message || '创建失败');
    }
  } catch (error) {
    console.error('创建便签失败:', error);
    uni.showToast({
      title: '创建失败',
      icon: 'none'
    });
  }
};

// 更新便签
const updateNote = async () => {
  try {
    const response = await notesApi.updateNote(editingNoteId.value, {
      title: noteForm.title.trim(),
      content: noteForm.content.trim()
    });

    if (response.code === 200) {
      // 更新列表中的便签
      const index = notesList.value.findIndex(note => note.id === editingNoteId.value);
      if (index !== -1) {
        notesList.value[index] = response.data;
      }
      // 备份到本地
      saveNotesToLocal();

      uni.showToast({
        title: '保存成功',
        icon: 'success'
      });

      closeNoteDialog();
    } else {
      throw new Error(response.message || '更新失败');
    }
  } catch (error) {
    console.error('更新便签失败:', error);
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    });
  }
};

// 删除便签
const deleteNote = (noteId) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条便签吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await notesApi.deleteNote(noteId);

          if (response.code === 200) {
            // 从列表中移除
            const index = notesList.value.findIndex(note => note.id === noteId);
            if (index !== -1) {
              notesList.value.splice(index, 1);
            }
            // 备份到本地
            saveNotesToLocal();

            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
          } else {
            throw new Error(response.message || '删除失败');
          }
        } catch (error) {
          console.error('删除便签失败:', error);
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          });
        }
      }
    }
  });
};
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: linear-gradient(135deg, #e8f5e9 0%, #f1f8e9 100%);
}

.status-bar {
  background-color: #4CAF50;
}

.navbar {
  height: 88rpx;
  background-color: #4CAF50;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(76, 175, 80, 0.2);
}

.nav-title {
  color: #ffffff;
  font-size: 36rpx;
  font-weight: 600;
}

.nav-add {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
}

.content {
  padding: 20rpx;
  padding-bottom: 120rpx;
}

.notes-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.note-item {
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  transition: transform 0.3s;
}

.note-item:active {
  transform: scale(0.98);
}

.note-info {
  width: 100%;
}

.note-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16rpx;
}

.note-title {
  font-size: 32rpx;
  color: #333333;
  font-weight: 600;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 16rpx;
}

.note-actions {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.action-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: #f5f5f5;
  transition: background-color 0.3s;
}

.action-btn:active {
  background-color: #e0e0e0;
}

.note-content {
  margin-bottom: 12rpx;
}

.content-preview {
  font-size: 28rpx;
  color: #666666;
  line-height: 1.5;
  word-wrap: break-word;
  word-break: break-all;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.note-time {
  margin-top: 8rpx;
}

.time-text {
  font-size: 22rpx;
  color: #999999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  text-align: center;
}

.empty-icon {
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #666666;
  margin-bottom: 16rpx;
}

.empty-hint {
  font-size: 28rpx;
  color: #999999;
  margin-bottom: 60rpx;
}

.note-container {
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
  overflow: hidden;
  width: 100%;
  box-sizing: border-box;
}

.note-header-popup {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #e0e0e0;
}

.note-title-popup {
  font-size: 32rpx;
  color: #333333;
  font-weight: 600;
}

.note-close {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.note-form {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
  overflow-x: hidden;
  width: 100%;
  box-sizing: border-box;
}

.form-item {
  margin-bottom: 30rpx;
  width: 100%;
  box-sizing: border-box;
}

.form-label-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333333;
  font-weight: 600;
}

.char-count {
  font-size: 24rpx;
  color: #999999;
  font-weight: normal;
}

.char-count.over-limit {
  color: #F44336;
  font-weight: 600;
}

.form-input {
  width: 100%;
  height: 80rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  color: #333333;
  background-color: #fafafa;
  box-sizing: border-box;
}

.form-input:focus {
  border-color: #4CAF50;
  background-color: #ffffff;
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  padding: 16rpx 24rpx;
  font-size: 28rpx;
  color: #333333;
  background-color: #fafafa;
  resize: none;
  line-height: 1.5;
  box-sizing: border-box;
}

.form-textarea:focus {
  border-color: #4CAF50;
  background-color: #ffffff;
}

.note-actions {
  display: flex;
  padding: 30rpx;
  gap: 20rpx;
  border-top: 1rpx solid #e0e0e0;
}

.note-btn {
  flex: 1;
  height: 80rpx;
  border: none;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: 600;
}

.note-btn.cancel {
  background-color: #f5f5f5;
  color: #666666;
}

.note-btn.confirm {
  background: linear-gradient(135deg, #4CAF50 0%, #66BB6A 100%);
  color: #ffffff;
}

.note-btn.confirm:disabled {
  background: #cccccc;
}
</style>
